package com.xyd.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyd.entity.Message;
import com.xyd.entity.User;
import com.xyd.service.UserService;
import com.xyd.service.impl.UserServiceImpl;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：
 *
 * @author 张吉哲
 * @date 2021/1/11 9:49
 */
@WebServlet("/userRegisterServlet")
public class UserRegisterServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    response.setContentType("application/json;charset=utf-8");
    Message message = new Message();

    String veryCode = request.getParameter("veryCode");
    String checkCode_server = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
    if (checkCode_server.equalsIgnoreCase(veryCode)) {
      request.getSession().removeAttribute("CHECKCODE_SERVER");
      String username = request.getParameter("userName");
      String password = request.getParameter("passWord");
      String sex = request.getParameter("sex");
      String birthday =
          request.getParameter("birthday").length() == 0 ? null : request.getParameter("birthday");
      String identityCard =
          request.getParameter("identityCard").length() == 0 ? null
              : request.getParameter("identityCard");
      String email =
          request.getParameter("email").length() == 0 ? null : request.getParameter("email");
      String phone =
          request.getParameter("phone").length() == 0 ? null : request.getParameter("phone");
      String address =
          request.getParameter("address").length() == 0 ? null : request.getParameter("address");

      sex = "男".equals(sex) ? "T" : "F";
      User user = new User(null, username, password, sex, birthday, identityCard, email, phone,
          address, 1);

      UserService userService = new UserServiceImpl();
      boolean flag = userService.registerUser(user);
      message.setFlag(flag);
      if (!flag) {
        message.setMessage("注册失败，请稍后再试");
      }
    } else {
      message.setFlag(false);
      message.setMessage("验证码错误");
    }
    mapper.writeValue(response.getOutputStream(), message);
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }
}
